const WebSocket = require('ws');

/**
 * 测试1033系统消息解析功能
 * 验证messageBody字符串是否正确解析为对象
 */

class SystemMessageTester {
    constructor() {
        this.ws = null;
        this.characterId = 1001; // 测试角色ID
    }

    async connect() {
        return new Promise((resolve, reject) => {
            console.log('🔌 连接WebSocket服务器...');

            this.ws = new WebSocket('ws://localhost:3001');

            this.ws.on('open', () => {
                console.log('✅ WebSocket连接成功');
                resolve();
            });

            this.ws.on('error', (error) => {
                console.error('❌ WebSocket连接失败:', error.message);
                reject(error);
            });

            this.ws.on('message', (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    this.handleMessage(message);
                } catch (error) {
                    console.error('❌ 解析消息失败:', error.message);
                }
            });
        });
    }

    handleMessage(message) {
        console.log('\n📨 收到消息:', JSON.stringify(message, null, 2));

        if (message.act_id === 1033) {
            console.log('\n🔍 分析1033系统消息响应:');

            if (message.code === 0) {
                console.log('✅ 查询成功');
                console.log(`📊 消息数量: ${message.list ? message.list.length : 0}`);

                if (message.list && message.list.length > 0) {
                    console.log('\n📋 消息列表分析:');
                    message.list.forEach((msg, index) => {
                        console.log(`\n消息 ${index + 1}:`);
                        console.log(`  类型: ${typeof msg}`);
                        console.log(`  内容:`, msg);

                        // 检查消息格式
                        if (typeof msg === 'object' && msg !== null) {
                            console.log('  ✅ 消息已正确解析为对象');

                            // 检查必要字段
                            const requiredFields = ['content', 'date', 'fname'];
                            const missingFields = requiredFields.filter(field => !(field in msg));

                            if (missingFields.length === 0) {
                                console.log('  ✅ 包含所有必要字段');
                                console.log(`    - content: ${msg.content}`);
                                console.log(`    - date: ${msg.date}`);
                                console.log(`    - fname: ${msg.fname}`);
                            } else {
                                console.log(`  ⚠️ 缺少字段: ${missingFields.join(', ')}`);
                            }
                        } else {
                            console.log('  ❌ 消息未正确解析为对象');
                            console.log(`  实际类型: ${typeof msg}`);
                        }
                    });
                } else {
                    console.log('📭 没有系统消息');
                }

                console.log('\n📋 附加信息:');
                console.log(`  - name: ${message.more?.name}`);
                console.log(`  - religion: ${message.more?.religion}`);
                console.log(`  - roleId: ${message.more?.roleId}`);

            } else {
                console.log('❌ 查询失败');
                console.log(`错误信息: ${message.msg}`);
            }
        }
    }

    async testSystemMessageQuery() {
        try {
            console.log('\n🧪 测试1033系统消息查询...');

            // 发送1033查询请求
            const request = {
                c: 1033,
                d: {
                    roleid: 1000 // 系统消息的roleid
                }
            };

            console.log('📤 发送请求:', JSON.stringify(request, null, 2));
            this.ws.send(JSON.stringify(request));

            // 等待响应
            await new Promise(resolve => setTimeout(resolve, 2000));

        } catch (error) {
            console.error('❌ 测试失败:', error.message);
        }
    }

    async testPersonalMessageQuery() {
        try {
            console.log('\n🧪 测试1033个人消息查询...');

            // 发送1033查询请求（个人消息）
            const request = {
                c: 1033,
                d: {
                    roleid: 1001 // 个人消息的roleid
                }
            };

            console.log('📤 发送请求:', JSON.stringify(request, null, 2));
            this.ws.send(JSON.stringify(request));

            // 等待响应
            await new Promise(resolve => setTimeout(resolve, 2000));

        } catch (error) {
            console.error('❌ 测试失败:', error.message);
        }
    }

    async runTests() {
        try {
            await this.connect();

            // 等待连接稳定
            await new Promise(resolve => setTimeout(resolve, 1000));

            // 测试系统消息查询
            await this.testSystemMessageQuery();

            // 等待一下再测试个人消息
            await new Promise(resolve => setTimeout(resolve, 1000));

            // 测试个人消息查询
            await this.testPersonalMessageQuery();

            console.log('\n🎉 测试完成');

        } catch (error) {
            console.error('❌ 测试执行失败:', error.message);
        } finally {
            if (this.ws) {
                this.ws.close();
                console.log('🔌 WebSocket连接已关闭');
            }
        }
    }
}

// 执行测试
if (require.main === module) {
    const tester = new SystemMessageTester();
    tester.runTests()
        .then(() => {
            console.log('\n✅ 1033系统消息解析测试完成');
            process.exit(0);
        })
        .catch((error) => {
            console.error('\n❌ 1033系统消息解析测试失败:', error.message);
            process.exit(1);
        });
}

module.exports = { SystemMessageTester };
